package com.ruoyi.flowable.listener;

import org.flowable.common.engine.api.delegate.event.FlowableEngineEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.FlowableActivityEvent;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.util.ArrayList;
import java.util.List;

import static org.flowable.common.engine.api.delegate.event.FlowableEngineEventType.*;

/**
 * @Description:
 * @Author: chen tao
 * @CreateTime: 2025-04-24
 */
@Configuration
public class FlowGlobalListener {
    @Lazy
    @Autowired
    private RuntimeService runtimeService;
    @Lazy
    @Autowired
    private TaskService taskService;
    @Bean
    public FlowableEventListener globalListener() {
        return new FlowableEventListener() {
            @Override
            public void onEvent(FlowableEvent event) {
                switch (event.getType().name()) {
                    // 1. 流程开始
                    case "PROCESS_STARTED":
                        String processInstanceId = ((FlowableEngineEvent) event).getProcessInstanceId();
                        String businessKey = runtimeService.createProcessInstanceQuery()
                                .processInstanceId(processInstanceId)
                                .singleResult()
                                .getBusinessKey();
                        System.out.println("[流程开始] 实例ID: " + processInstanceId + ", 业务Key: " + businessKey);
                        break;

                    // 2. 流程正常结束
                    case "PROCESS_COMPLETED":
                        String endedProcessId = ((FlowableEngineEvent) event).getProcessInstanceId();
                        System.out.println("[流程结束] 实例ID: " + endedProcessId);
                        break;

                    // 3. 审批（任务完成）
                    case "TASK_COMPLETED":
                        FlowableEngineEvent taskEvent = (FlowableEngineEvent) event;
                        Task task = taskService.createTaskQuery()
                                .taskId(taskEvent.getProcessInstanceId()) // 获取任务ID
                                .singleResult();

                        if (task != null) {
                            String taskName = task.getName();
                            String assignee = task.getAssignee();
                            System.out.println("[任务审批] 任务名称: " + taskName + ", 处理人: " + assignee);
                        }
                        break;

                    // 4. 驳回（需结合业务判断）
                    case "ACTIVITY_COMPLETED":
                        FlowableActivityEvent activityEvent = (FlowableActivityEvent) event;
                        if ("userTask".equals(activityEvent.getActivityType())) {
                            // 检查是否回退到上一个节点（需根据实际业务逻辑判断）
                            System.out.println("[可能驳回] 活动ID: " + activityEvent.getActivityId());
                        }
                        break;
                }
            }

            @Override
            public boolean isFailOnException() {
                return false;
            }

            @Override
            public boolean isFireOnTransactionLifecycleEvent() {
                return false;
            }

            @Override
            public String getOnTransaction() {
                return null;
            }
        };
    }
    @Bean
    public SpringProcessEngineConfiguration processEngineConfiguration() {
        SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();
        List<FlowableEventListener> list = new ArrayList<>();
        list.add(globalListener());
        config.setEventListeners(list); // 注册监听器
        return config;
    }
}
